#include "scene_main.h"

#include <fstream>

#include "player.h"
#include "scene_title.h"
#include "spawner.h"
#include "raw/bg_star.h"
#include "screen/hud_stats.h"
#include "screen/hud_text.h"
#include "screen/ui_mouse.h"
#include "world/spell.h"

void SceneMain::init() {
    SDL_HideCursor();
    game_.playMusic("resources/bgm/OhMyGhost.ogg");
    // SDL_ShowCursor();
    world_size_ = game_.getScreenSize() * 3.0f; // 获取世界大小
    camera_pos_ = glm::vec2(world_size_ / 2.0f - game_.getScreenSize() / 2.0f); // 摄像机位置
    player_ = new Player(); // 创建玩家
    player_->init(); // 初始化玩家
    player_->setPosition(world_size_ / 2.0f); // 设置玩家位置
    addChild(player_); // 添加玩家到场景

    BgStar::addBgStarChild(this, 2000, 0.2, 0.5, 0.7);

    end_timer_ = Timer::addTimerChild(this, 3);
    spawner_ = new Spawner();
    spawner_->init();
    spawner_->setTarget(player_);
    addChild(spawner_);
    button_pause_ = HUDButton::addHUDButtonChild(this, game_.getScreenSize() - glm::vec2(230, 30),
                                                 "resources/UI/A_Pause1.png",
                                                 "resources/UI/A_Pause2.png",
                                                 "resources/UI/A_Pause1.png");
    button_restart_ = HUDButton::addHUDButtonChild(this, game_.getScreenSize() - glm::vec2(140, 30),
                                                   "resources/UI/A_Restart1.png",
                                                   "resources/UI/A_Restart2.png",
                                                   "resources/UI/A_Restart3.png");
    button_back_ = HUDButton::addHUDButtonChild(this, game_.getScreenSize() - glm::vec2(40, 30),
                                                "resources/UI/A_Back1.png", "resources/UI/A_Back2.png",
                                                "resources/UI/A_Back3.png");

    hud_stats_ = HUDStats::addHUDStatsChild(this, player_, glm::vec2(30.f));
    hud_text_ = HUDText::addHUDTextChild(this, "Score: 0", glm::vec2(200, 50),
                                         glm::vec2(game_.getScreenSize().x - 120.f, 30)
    );
    ui_mouse_ = UIMouse::addUIMouseChild(this, "resources/UI/29.png", "resources/UI/30.png", 1.0f, Anchor::CENTER);
}

void SceneMain::update(float dt) {
    checkSlowDown(dt);
    Scene::update(dt); // 更新场景
    updateScore();
    if (player_ && !player_->getActive()) {
        //角色死亡
        static bool first = true;
        if (first) {
            first = false;
            saveData("resources/score.dat");
        }
        end_timer_->start();
    }
    checkButtonBack();
    checkButtonPause();
    checkButtonRestart();
    checkEndTimer();
}

void SceneMain::render() {
    rendererBackground(); // 渲染背景
    Scene::render(); // 渲染场景
}

void SceneMain::clean() {
    Scene::clean(); // 清理场景
}

bool SceneMain::handleEvents(SDL_Event &event) {
    Scene::handleEvents(event); // 处理事件
    return false;
}

void SceneMain::updateScore() {
    hud_text_->setText("Score: " + std::to_string(game_.getScore()));
}

void SceneMain::checkButtonPause() {
    if (button_pause_->isTrigger()) {
        SDL_Log("Button pause");
        if (is_paused_) {
            game_.resumeMusic();
            resume();
        } else {
            game_.pauseMusic();
            pause();
        }
        button_pause_->setIsTrigger(false);
    }
}

void SceneMain::checkButtonBack() {
    if (button_back_->isTrigger()) {
        auto scene = new SceneTitle();
        game_.safeChangeScene(scene);
        button_back_->setIsTrigger(false);
        saveData("resources/score.dat");
    }
}

void SceneMain::checkButtonRestart() {
    if (button_restart_->isTrigger()) {
        auto scene = new SceneMain();
        game_.safeChangeScene(scene); //->clean->init
        button_restart_->setIsTrigger(false);
        saveData("resources/score.dat");
    }
}

void SceneMain::checkEndTimer() {
    if (end_timer_->timeOut()) {
        pause();
        button_restart_->setRenderPos(game_.getScreenSize() / 2.0f - glm::vec2(200, 0));
        button_restart_->setScale(4);
        auto pos = game_.getScreenSize() / 2.0f + glm::vec2(200, 0);
        button_back_->setRenderPos(pos);
        button_back_->setScale(4);
        button_pause_->setActive(false);
        end_timer_->stop();
    }
}

void SceneMain::saveData(const std::string &file_path) {
    Scene::saveData(file_path);
    int high_score = game_.getHighScore();
    std::ofstream file(file_path, std::ios::binary);
    if (file.is_open()) {
        file.write(reinterpret_cast<const char *>(&high_score), sizeof(int));
        SDL_Log("保存最高分：%d", high_score);
        file.close();
    }
}

void SceneMain::checkSlowDown(float &dt) {
    if (game_.getMouseButtonFlags() & SDL_BUTTON_RMASK) {
        dt *= 0.4;
    }
}

void SceneMain::rendererBackground() {
    const auto start = -camera_pos_;
    const auto end = world_size_ - camera_pos_;
    game_.drawGrid(start, end, 80.0f, {0.5, 0.5, 0.5, 0.5}); // 渲染网格
    game_.drawBoundry(start, end, 5.0f, {1.0, 1.0, 1.0, 1.0}); // 渲染边界
}
